package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.entity.SetmealDto;
import com.itheima.reggie.exception.CustomException;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper,Setmeal> implements SetmealService {

    @Autowired
    SetmealDishService setmealDishService;


    @Override
    @Transactional
    public void saveWithDish(SetmealDto dto) {
        //1.保存套餐的基本信息
        save(dto);
        //2.保存套餐和菜品的关连信息
        //2.1获取到套餐的id,并设置到关联集合中
        Long setmealId = dto.getId();//套餐的id
        List<SetmealDish> setmealDishes = dto.getSetmealDishes();
        setmealDishes.forEach(setmealDish -> setmealDish.setSetmealId(setmealId));
        //2.2 批量保存到数据库
        setmealDishService.saveBatch(setmealDishes);
    }

    @Autowired
    SetmealMapper setmealMapper;
    @Override
    public Page<SetmealDto> pageByName(int page, int pageSize, String name) {
        Page<SetmealDto> pageInfo = new Page<>(page, pageSize);

        return setmealMapper.pageByName(pageInfo,name);
    }
    //根据id集合删除 套餐id集合
    @Override
    public void deleteByIds(List<Long> ids) {
        //1.判断这些套餐中是否包含起售的套餐 但凡有一个 不允许删除 抛出业务异常
        LambdaQueryWrapper<Setmeal> setmealLqw = new LambdaQueryWrapper<>();
        setmealLqw.in(Setmeal::getId,ids);
        setmealLqw.eq(Setmeal::getStatus,1);
        long count = count(setmealLqw);
        if (count>0){
            throw new CustomException("存在起售套餐不允许删除");
        }
        //2.删除套餐基本信息
        removeByIds(ids);
        //3.删除套餐和菜品的
        LambdaQueryWrapper<SetmealDish> sdLqw = new LambdaQueryWrapper<>();
        sdLqw.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(sdLqw);



    }
}
